#include "webglk.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

void webglk_open()
{
	printf("Content-Type: text/plain;charset=utf8\n\n");
	printf("[\n");
	glk_stream_buffer_open();
}
void webglk_close()
{
	glk_stream_buffer_close();
	printf("]\n");
}
void glk_stylehint_set(glui32 wintype,glui32 styl,glui32 hint,glsi32 val)
{
	glk_stream_buffer_flush();
        printf("{m:'stylehint',w:%u,s:%u,h:%u,v:",wintype,styl,hint);
	if (hint==stylehint_TextColor || hint==stylehint_BackColor)
		printf("'#%02x%02x%02x'",(val>>16)&0xff,(val>>8)&0xff,val&0xff);
	else
		printf("%d",val);
        printf("},\n");
}
void glk_stylehint_clear(glui32 wintype,glui32 styl,glui32 hint)
{
	glk_stream_buffer_flush();
	printf("{m:'stylehint',w:%u,s:%u,h:%u},\n",wintype,styl,hint);
}
void glk_set_style(glui32 val)
{
	glk_stream_buffer_flush();
	printf("{m:'style',s:%u},\n",val);
}
void glk_request_line_event(winid_t win,char *buf,glui32 maxlen,glui32 initlen)
{
	int i;
	glk_stream_buffer_flush();
	printf("{m:'readline',w:%u,i:[",win);
	for (i=0;i<initlen;i++)
		printf("%s%d",i?",":"",buf[i]);
	printf("]},\n");
}
void glk_request_char_event(winid_t win)
{
	glk_stream_buffer_flush();
	printf("{m:'readchar',w:%u},\n",win);
}
void glk_cancel_char_event(winid_t win)
{
	glk_stream_buffer_flush();
	printf("{m:'xreadchar',w:%u},\n",win);
}
void glk_request_timer_events(glui32 millisecs)
{
	glk_stream_buffer_flush();
	printf("{m:'timer',t:%u},\n",millisecs);
}

void fatal(const char *fmt,...)
{
	va_list arg;
	va_start(arg,fmt);
	glk_stream_buffer_flush();
	printf("{e:\"");
	vprintf(fmt,arg);
	printf("\"}");
	va_end(arg);
	webglk_close();
	exit(-1);
}
void webglk_load(FILE *f)
{
	glk_window_load(f);
	glk_stream_load(f);
	glk_fileref_load(f);
}
void webglk_save(FILE *f)
{
	glk_window_save(f);
	glk_stream_save(f);
	glk_fileref_save(f);
}
